<!DOCTYPE html>
<html lang="ch">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>3.使正方形旋转</title>
</head>

<body onload="main()">
  <canvas id="glcanvas" width="640" height="480">
    你的浏览器似乎不支持或者禁用了HTML5 <code>&lt;canvas&gt;</code> 元素.
  </canvas>

  <script src="./static/js/gl-matrix-min.js"></script>

  <script>
    /**
     * 1.创建一个变量，用于跟踪正方形的当前旋转
     * 2.更新drawScene()函数以在绘制正方形时将当前旋转应用于正方形
     * 3.创建一个新变量来跟踪上次动画播放的时间
    */

    var mat4 = glMatrix.mat4;
    var squareRotation = 0.0;

    function main() {
      var canvas = document.getElementById('glcanvas')
      var gl = canvas.getContext("webgl")

      if (!gl) {
        alert('不支持webgl')
        return;
      }

      const vsSource = `
        attribute vec3 aVertexPosition;
        attribute vec4 aVertexColor;
      
        uniform mat4 uModelViewMatrix;
        uniform mat4 uProjectionMatrix;

        varying lowp vec4 vColor;

        void main() {
          gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aVertexPosition, 1.0);;
          vColor = aVertexColor;
        }
      `;

      const fsSource = `
        varying lowp vec4 vColor;
        void main() {
         gl_FragColor = vColor;
        }
      `;

      const shaderProgram = initShaderProgram(gl, vsSource, fsSource)

      const programInfo = {
        program: shaderProgram,
        attribLocations: {
          vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
          vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor")
        },
        uniformLocations: {
          projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
          modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
        },
      };

      var buffers = initBuffers(gl)
      var then = 0;
      // 
      function render(now) {
        now *= 0.001
        const deltaTime = now - then
        then = now

        drawScene(gl, programInfo, buffers, deltaTime)
        squareRotation += deltaTime;

        requestAnimationFrame(render)
      }

      requestAnimationFrame(render);
    }


    // 初始化着色器
    function initShaderProgram(gl, vsSource, fsSource) {
      const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource)
      const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);

      const shaderProgram = gl.createProgram()
      gl.attachShader(shaderProgram, vertexShader)
      gl.attachShader(shaderProgram, fragmentShader)

      gl.linkProgram(shaderProgram)

      if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
        alert('初始化着色器失败')
        return null
      }
      return shaderProgram;
    }

    function loadShader(gl, type, source) {
      const shader = gl.createShader(type)
      gl.shaderSource(shader, source)
      gl.compileShader(shader)

      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert('初始化着色器失败')
        gl.deleteShader(shader);
        return null
      }
      return shader
    }


    function initBuffers(gl) {
      const positionBuffer = gl.createBuffer()
      gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)

      var vertices = [
        1.0, 1.0, 0.0,
        -1.0, 1.0, 0.0,
        1.0, -1.0, 0.0,
        -1.0, -1.0, 0.0
      ]

      const positions = [
        1.0, 1.0,
        -1.0, 1.0,
        1.0, -1.0,
        -1.0, -1.0,
      ];

      gl.bufferData(gl.ARRAY_BUFFER,
        new Float32Array(positions),
        gl.STATIC_DRAW)


      const colorBuffer = gl.createBuffer()
      const colors = [
        1.0, 1.0, 1.0, 1.0,    // 白
        1.0, 0.0, 0.0, 1.0,    // 红
        0.0, 1.0, 0.0, 1.0,    // 绿
        00, 0.0, 1.0, 1.0,    // 蓝
      ]
      gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer)
      gl.bufferData(gl.ARRAY_BUFFER,
        new Float32Array(colors),
        gl.STATIC_DRAW
      )

      return {
        position: positionBuffer,
        color: colorBuffer,
      }
    }

    // 渲染场景
    function drawScene(gl, programInfo, buffers) {
      gl.clearColor(0.0, 0.0, 0.0, 1.0);
      gl.clearDepth(1.0)
      gl.enable(gl.DEPTH_TEST)
      gl.depthFunc(gl.LEQUAL)

      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)


      const fieldOfView = 45 * Math.PI / 180
      const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight
      const zNear = 0.1
      const zFar = 100.0
      const projectionMatrix = mat4.create()

      mat4.perspective(projectionMatrix,
        fieldOfView,
        aspect,
        zNear,
        zFar
      )

      const modelViewMatrix = mat4.create()
      mat4.translate(modelViewMatrix,  //目的地矩阵
        modelViewMatrix, // 翻转矩阵
        [-0.0, 0.0, -6.0] // 翻转量
      )

      // 将modelViewMatrix的当前值squareRotation绕Z轴旋转
      mat4.rotate(modelViewMatrix,
        modelViewMatrix,
        squareRotation,
        [0, 0, 1]
      )

      {
        const numComponents = 2   //每次迭代提取2个值
        const type = gl.FLOAT     // buffer 类型是32bit float
        const normalize = false   // 不使用标准化
        const stride = 0           //从一组值到下一组值需要多少字节
        const offset = 0           //从缓冲区内多少字节开始  

        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position)
        // 绘制正方形时使用颜色
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position)
        gl.vertexAttribPointer(
          programInfo.attribLocations.vertexPosition,
          numComponents,
          type,
          normalize,
          stride,
          offset
        )
        gl.enableVertexAttribArray(
          programInfo.attribLocations.vertexPosition
        )
      }

      // 初始化颜色属性
      {
        const numComponents = 4   //每次迭代提取4个值
        const type = gl.FLOAT     // buffer 类型是32bit float
        const normalize = false   // 不使用标准化
        const stride = 0           //从一组值到下一组值需要多少字节
        const offset = 0           //从缓冲区内多少字节开始  

        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color)
        // 绘制正方形时使用颜色
        gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color)
        gl.vertexAttribPointer(
          programInfo.attribLocations.vertexColor,
          numComponents,
          type,
          normalize,
          stride,
          offset
        )
        gl.enableVertexAttribArray(
          programInfo.attribLocations.vertexColor
        )
      }

      gl.useProgram(programInfo.program)

      gl.uniformMatrix4fv(
        programInfo.uniformLocations.projectionMatrix,
        false,
        projectionMatrix
      )
      gl.uniformMatrix4fv(
        programInfo.uniformLocations.modelViewMatrix,
        false,
        modelViewMatrix
      )
      {
        const offset = 0
        const vertexCount = 4
        // 画出对象
        gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount)
      }
    }
  </script>
</body>

</html>